
package cn.xabad.commons.plist;

import android.util.Log;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


public abstract class BaseXMLParser {

	public static final String TAG = "BaseXMLParser";

	
	protected Stringer stringer;

	
	private DefaultHandler handler;

	
	protected SAXParserFactory spf;

	
	protected SAXParser sp;

	
	public BaseXMLParser() {
		stringer = new Stringer();
	}

	
	public DefaultHandler getHandler() {
		return handler;
	}

	
	public void setHandler(DefaultHandler handler) {
		this.handler = handler;
	}

	
	public void initParser() {
		
		if (null == spf) {
			spf = SAXParserFactory.newInstance();
		}
		
		try {
			sp = spf.newSAXParser();
		} catch (ParserConfigurationException e) {
			Log.e(
                    stringer.newBuilder().append(TAG).append("#parse")
                            .toString(), "ParserConfigurationException");
		} catch (SAXException e) {
			Log.e(
                    stringer.newBuilder().append(TAG).append("#parse")
                            .toString(), "SAXException");
		}
	}

	
	public void parse(String xml) throws IllegalStateException {
		try {
			
			InputSource inSrc = new InputSource(new StringReader(xml));
			
			sp.parse(inSrc, getHandler());
		} catch (SAXException e) {
			Log.e(
                    stringer.newBuilder().append(TAG).append("#parse")
                            .toString(), "SAXException");
		} catch (IOException e) {
			Log.e(
                    stringer.newBuilder().append(TAG).append("#parse")
                            .toString(), "IOException");
		}

		Log.v(stringer.newBuilder().append(TAG).append("#parse").toString(),
                "done parsing xml");
	}

}
